/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dal;

import bean.Argument;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import util.HibernateUtil;

/**
 *
 * @author HoangNam
 */
public class QuanAoDAL<T> {

    private Session session;
    private Transaction ts;

    public QuanAoDAL() {
    }

    private void callSession() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
        this.ts = this.session.beginTransaction();
    }

    public void insert(T obj) {
        callSession();
        this.session.save(obj);
        this.ts.commit();
    }

    public T getByIDForIdentityColumn(int id, T cl) {
        callSession();
        T obj = (T) this.session.get(cl.getClass(), id);
        this.ts.commit();
        return obj;
    }

    public List<T> getListResult(String query, Argument[] arr) {
        callSession();
        Query q = this.session.createQuery(query);
        if (arr != null) {
            for (Argument arg : arr) {
                q.setParameter(arg.getKey(), arg.getValue());
            }
        }
        List<T> list = q.list();
        this.ts.commit();
        return list;
    }

    public T getSingleResult(String query, Argument[] arr) {
        callSession();
        Query q = this.session.createQuery(query);
        for (Argument arg : arr) {
            q.setParameter(arg.getKey(), arg.getValue());
        }
        T result = (T) q.uniqueResult();
        this.ts.commit();
        return result;
    }

    public void delete(T obj) {
        callSession();
        this.session.delete(obj);
        this.ts.commit();
    }
}
